package net.zm123.async;

import com.nfk.grpc.MyServiceGrpc;
import com.nfk.grpc.MyServiceOuterClass;
import io.grpc.ManagedChannel;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.CountDownLatch;

public class RpcAsyncClient {
    /**
     * 异步凭据
     */
    private MyServiceGrpc.MyServiceStub asyncStub;
    private CountDownLatch latch;

    public RpcAsyncClient(CountDownLatch latch,ManagedChannel channel) {
        this.latch = latch;
        this.asyncStub = MyServiceGrpc.newStub(channel);
    }

    public void testActionMethod() {
        MyServiceOuterClass.ActionRequest request = MyServiceOuterClass.ActionRequest.newBuilder()
                //todo
                .setTerminalId("test")
                .setThreshold(123)
                .build();
        this.asyncStub.actionMethod(request, new StreamObserver<MyServiceOuterClass.ActionResponse>() {
            @Override
            public void onNext(MyServiceOuterClass.ActionResponse response) {
                //收到返回
                if (response != null) {
                    String message = response.getMessage();
                    System.out.println(message);
                }
                latch.countDown();
            }

            @Override
            public void onError(Throwable throwable) {
                // 处理异常
                System.err.println("Error occurred: " + throwable.getMessage());
                latch.countDown();
            }

            @Override
            public void onCompleted() {
                // 完成回调
                System.out.println("gRPC call completed.");
                latch.countDown();
            }
        });
    }
}
